package main

import (
	"fmt"
	"github.com/robertkrimen/otto"
)

type jsCaller struct {
	vm     *otto.Otto
	method otto.Value
	obj    otto.Value
}

func (c *jsCaller) CheckResult(req, resp string) bool {
	v, e := c.method.Call(c.obj, req, resp)
	if e != nil {
		return false
	}
	r, e := v.ToBoolean()
	if e != nil {
		return false
	}
	return r
}

/**
 * script 是方法主题,用于检查返回结果是否正确, req 为请求数据 resp 为返回数据, 必须返回 bool
 * 如
 *    return req==resp;
 */
func NewJsCaller(script string) (*jsCaller, error) {
	vm := otto.New()

	s, err := vm.Compile("", fmt.Sprintf("var ck=function(req,resp) { %s }", script))
	if err != nil {
		return nil, err
	}
	obj, err := vm.Run(s)
	if err != nil {
		return nil, err
	}
	method, err := vm.Get("ck")
	if err != nil {
		return nil, err
	}
	return &jsCaller{
		vm:     vm,
		method: method,
		obj:    obj,
	}, nil
}
